package shuashuami.hb.com.avtivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import shuashuami.hb.com.hbclient.R;
import shuashuami.hb.com.hdlibrary.util.ToastUtil;
import shuashuami.hb.com.http.HttpMethods;
import shuashuami.hb.com.http.HttpOnNextListener;
import shuashuami.hb.com.http.LoginHttp;
import shuashuami.hb.com.http.UploadErrorHttp;
import shuashuami.hb.com.manager.HbAppManager;
import shuashuami.hb.com.share.ShareCUserInfo;
import shuashuami.hb.com.util.SystemUtil;
import shuashuami.hb.com.view.IsHaveDailiBianmaDialog;

public class BindPhonenumActivity extends AbActivity {

    private EditText edtPhoneNum, edtCode;
    private TextView tvGetCode, tvCodeCountDown;
    private Button btnNext;

    private int recLen = 60;
    private boolean isGetCode = true;
    private ProgressDialog progressDialog;
    @Override
    protected void initUI() {
        setAbContentView(R.layout.activity_bind_phonenum);
        setLeftView();
        edtPhoneNum = (EditText) findViewById(R.id.edt_bind_phone_num_phone_num);
        edtCode = (EditText) findViewById(R.id.edt_bind_phone_num_code);
        tvGetCode = (TextView) findViewById(R.id.tv_bind_phone_num_get_code);
        tvCodeCountDown = (TextView) findViewById(R.id.tv_bind_phone_num_count_down);
        btnNext = (Button) findViewById(R.id.btn_bind_phone_num_next);
    }

    @Override
    protected void initData() {
        setTitleBar("绑定手机号码");
    }

    @Override
    protected void initListener() {
        setLeftViewListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkAccount()) {
                    bindPhoneNum();
                }
            }
        });
        tvGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isGetCode) {
                    getCode();
                } else {
                    ToastUtil.showShort(BindPhonenumActivity.this, "请勿重复点击");
                }
            }
        });

    }

    public void getCode() {
        isGetCode = false;
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                Message message = handler.obtainMessage(2);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };

        HttpMethods.getCode(listener,
                edtPhoneNum.getText().toString(), "bind"
        );
    }

    private void bindPhoneNum() {
        progressDialog = ProgressDialog.show(this, "加载...", "请稍后...", true, false);
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                Message message = handler.obtainMessage(3);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };

        HttpMethods.bindPhoneNum(listener,
                edtPhoneNum.getText().toString(), edtCode.getText().toString()
        );
    }

    private void countDown() {
        tvCodeCountDown.setVisibility(View.VISIBLE);
        Message message = handler.obtainMessage(1);     // Message
        handler.sendMessageDelayed(message, 1000);

    }

    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    recLen--;
                    tvCodeCountDown.setText("" + recLen);

                    if (recLen > 0) {
                        Message message = handler.obtainMessage(1);
                        handler.sendMessageDelayed(message, 1000);      // send message
                    } else {
                        isGetCode = true;
                        recLen = 60;
                        tvCodeCountDown.setVisibility(View.GONE);
                    }
                    break;
                case 2:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("status") == 203) {
                            LoginHttp loginHttp = new LoginHttp(BindPhonenumActivity.this);
                            loginHttp.login();
                            return;
                        }
                        if (jsonObject.getInt("status") == 200) {
                            ToastUtil.showShort(BindPhonenumActivity.this, "获取成功");
                            countDown();
                        } else {
                            isGetCode = true;
                            ToastUtil.showShort(BindPhonenumActivity.this, jsonObject.getString("message"));

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 3:
                    progressDialog.dismiss();
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("status") == 203) {
                            LoginHttp loginHttp = new LoginHttp(BindPhonenumActivity.this);
                            loginHttp.login();
                            return;
                        }
                        if (jsonObject.getInt("status") == 200) {
                            int tag = HbAppManager.getInstance().getTypeValue();
                            ShareCUserInfo shareCUserInfo = new ShareCUserInfo(BindPhonenumActivity.this);
                            shareCUserInfo.setPhoneNum(edtPhoneNum.getText().toString());
                            //   openActivity(CPerfectDataActivity.class);
                            if (tag == 1) {
                                toPerfect();
                            } else {
                                Intent intent = new Intent();
                                intent.putExtra("phone", edtPhoneNum.getText().toString());
                                intent.setClass(BindPhonenumActivity.this, CPerfectDataActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        } else if (jsonObject.getString("message").equals("手机号不正确")) {
                            upload();
                        } else {
                            ToastUtil.showShort(BindPhonenumActivity.this, jsonObject.getString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
            }

            super.handleMessage(msg);
        }
    };

    private void upload() {
        UploadErrorHttp uploadErrorHttp = new UploadErrorHttp(this);
        uploadErrorHttp.upload(String.format(String.format("手机号：" + edtPhoneNum.getText().toString()
                + "验证码" + edtCode.getText().toString() +
                "手机厂商：" + SystemUtil.getDeviceBrand() + "手机型号：" + SystemUtil.getSystemModel() +
                "Android系统版本号：" + SystemUtil.getSystemVersion() + "cookie：" + HbAppManager.getClearableCookieJar())));

    }

    private void toPerfect() {
        IsHaveDailiBianmaDialog isHaveDailiBianmaDialog = new IsHaveDailiBianmaDialog(this, edtPhoneNum.getText().toString());
        isHaveDailiBianmaDialog.show();
    }

    private boolean checkAccount() {
        if (edtPhoneNum.getText().toString().trim().isEmpty()) {
            edtPhoneNum.setError("号码不能为空");
            edtPhoneNum.requestFocus();
            return false;
        }
        if (edtCode.getText().toString().trim().isEmpty()) {
            edtCode.setError("验证码不能为空");
            edtCode.requestFocus();
            return false;
        }
        return true;
    }
}
